package io.cloud.tec.project.component;

import io.cloud.tec.project.dto.AccountDTO;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;


@Component
public class TimeHandler {
    public Mono<ServerResponse> getTime(ServerRequest serverRequest) {
        return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(
                Mono.just("Now is " + DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalTime.now())), String.class);
    }

    public Mono<ServerResponse> getDate(ServerRequest serverRequest) {
        return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(
                Mono.just("Today is " + DateTimeFormatter.ISO_DATE.format(LocalDate.now())), String.class);
    }

    public Mono<ServerResponse> sendTimePerSec(ServerRequest serverRequest) {
        // SSE
        return ServerResponse.ok().contentType(MediaType.TEXT_EVENT_STREAM).body(
                Flux.interval(Duration.ofSeconds(1)).map(s -> DateTimeFormatter.ofPattern("HH:mm:ss").format(LocalTime.now())), String.class);
    }

    public Mono<ServerResponse> streamJson(ServerRequest serverRequest) {
        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_NDJSON)
                .contentType(MediaType.APPLICATION_STREAM_JSON)
                .body(
                Flux.interval(Duration.ofSeconds(1)).map(a -> new AccountDTO()).delayElements(Duration.ofSeconds(1)), AccountDTO.class);
    }
}